import cv2
import os

# 打开摄像头
cap = cv2.VideoCapture(0)

if not cap.isOpened():
    print("RGB camera not found")
    exit()

print("Press 'q' to quit, 'b' to save image.")

# 创建 captures 文件夹
save_dir = os.path.join(os.getcwd(), "captures")
os.makedirs(save_dir, exist_ok=True)

# 图片计数器
img_counter = 0

while True:
    ret, frame = cap.read()
    if not ret:
        print("Failed to get frame.")
        break

    # 水平翻转（镜像）
    frame = cv2.flip(frame, 1)

    # 显示窗口
    cv2.imshow("RGB Camera (Flipped)", frame)

    key = cv2.waitKey(1) & 0xFF

    # 按 'b' 保存图片
    if key == ord('b'):
        filename = f"{img_counter:02d}.jpg"  # 00.jpg, 01.jpg, ...
        filepath = os.path.join(save_dir, filename)
        cv2.imwrite(filepath, frame)
        print(f"✅ Saved: {filepath}")
        img_counter += 1

    # 按 'q' 退出
    elif key == ord('q'):
        print("Exiting...")
        break

# 释放资源
cap.release()
cv2.destroyAllWindows()
